<template>
  <div class="app-container" ref="appcontainer">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="门店名称" prop="storeName">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入门店名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="门店电话" prop="storePhone">
        <el-input
          v-model="queryParams.storePhone"
          placeholder="请输入门店电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="邀请码" prop="agentCode">
        <el-input
          v-model="queryParams.agentCode"
          placeholder="请输入邀请码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="运营状态" prop="showState">
        <el-select v-model="queryParams.showState" placeholder="请选择运营状态" clearable size="small">
          <el-option
            v-for="dict in showStateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="门店状态" prop="storeState">
        <el-select v-model="queryParams.storeState" placeholder="请选择门店状态" clearable size="small">
          <el-option
            v-for="dict in storeStateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"  size="mini" @click="handleQuery">搜索</el-button>
        <el-button  size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain

          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['store:store:edit']"
        >查看</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain

          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['store:store:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain

          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['store:store:export']"
          v-if="false"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :height="tableHeight" :data="storeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" v-if="false" />
      <el-table-column label="门店名称" align="center" prop="storeName" />
      <el-table-column label="门店电话" align="center" prop="storePhone" />
      <el-table-column label="门店地址" align="center" prop="addressName" />
      <el-table-column label="运营状态" align="center" prop="showState">
        <template slot-scope="scope">
          <dict-tag :options="showStateOptions" :value="scope.row.showState"/>
        </template>
      </el-table-column>
      <el-table-column label="营业额" align="center" prop="storeRevenue" />
      <el-table-column label="订单数" align="center" prop="storeOrderCount" />
      <el-table-column label="员工数" align="center" prop="storeStaffCount" />
      <el-table-column label="门店状态" align="center" prop="storeState">
        <template slot-scope="scope">
          <dict-tag :options="storeStateOptions" :value="scope.row.storeState"/>
        </template>
      </el-table-column>
      <el-table-column label="人均消费" align="center" prop="consumption" />
      <el-table-column label="省名称" align="center" prop="provinceName" />
      <el-table-column label="市名称" align="center" prop="cityName" />
      <el-table-column label="邀请码" align="center" prop="agentCode" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"

            @click="handleUpdate(scope.row)"
            v-hasPermi="['store:store:edit']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"

            @click="handleToProduct(scope.row)"
            v-hasPermi="['store:store:edit']"
          >门店产品</el-button>
          <el-button
            size="mini"
            type="text"

            @click="handleToTechnician(scope.row)"
            v-hasPermi="['store:store:edit']"
          >门店技师</el-button>
          <el-button
            size="mini"
            type="text"
            @click="toStaffList(scope.row)"
          >员工列表</el-button>
          <el-button
            size="mini"
            type="text"

            @click="handleStoreShow(scope.row)"
            v-hasPermi="['store:store:show']"
          >门店展示</el-button>

          <el-button
            size="mini"
            type="text"
            @click="updateAgentCode(scope.row)"
            v-hasPermi="['store:store:remove']"
          >修改邀请码</el-button>

          <el-button
            size="mini"
            type="text"

            @click="handleDelete(scope.row)"
            v-hasPermi="['store:store:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或查看门店对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="门店logo">
              <ImageScan v-model="form.storeImage"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="店内环境">
              <ImageScan v-model="form.storeBacImage"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="营业执照" prop="businessImage">
          <ImageScan v-model="form.businessImage"/>
        </el-form-item>
        <el-form-item label="门店名称" prop="storeName">
          <el-input v-model="form.storeName" placeholder="请输入门店名称" readonly />
        </el-form-item>
        <el-form-item label="门店电话" prop="storePhone">
          <el-input v-model="form.storePhone" placeholder="请输入门店电话" readonly />
        </el-form-item>
        <el-form-item label="门店地址" prop="addressName">
          <el-input v-model="form.addressName" type="textarea" placeholder="请输入内容" readonly />
        </el-form-item>
        <el-form-item label="定位地址" prop="location">
          <el-input v-model="form.location" type="textarea" placeholder="请输入内容"readonly />
        </el-form-item>
        <el-form-item label="品牌介绍" prop="brandDetail">
          <el-input v-model="form.brandDetail" type="textarea" placeholder="请输入内容" readonly />
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="运营状态" prop="showState"  disabled readonly>
              <el-select v-model="form.showState" placeholder="请选择运营状态" >
                <el-option
                  v-for="dict in showStateOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店状态" prop="storeState">
              <el-select v-model="form.storeState" placeholder="请选择门店状态">
                <el-option
                  v-for="dict in storeStateOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>


        <el-form-item label="人均消费" prop="consumption">
          <el-input v-model="form.consumption" placeholder="请输入人均消费" readonly/>
        </el-form-item>
        <el-form-item label="服务保障" prop="serviceItem">
          <el-input v-model="serviceItem" type="textarea" placeholder="请输入内容" readonly />
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="营业开始时间" prop="businessStart">
              <el-input v-model="form.businessStart" placeholder="开始营业时间" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束营业时间" prop="businessEnd">
            <el-input v-model="form.businessEnd" placeholder="结束营业时间" readonly/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="省名称" prop="provinceName">
              <el-input v-model="form.provinceName" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="市名称" prop="cityName">
              <el-input v-model="form.cityName"  readonly/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="6">
            <el-form-item label="综合星级" prop="storeLevel">
              <el-input v-model="form.storeLevel"  readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="效果星级" prop="effectLevel">
              <el-input v-model="form.effectLevel"  readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="环境星级" prop="environmentLevel">
              <el-input v-model="form.environmentLevel"  readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="服务星级" prop="serviceLevel">
              <el-input v-model="form.serviceLevel" readonly/>
            </el-form-item>
          </el-col>
        </el-row>

<!--        <el-row>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="银行卡开户行" prop="bankDeposit" >-->
<!--              <el-input v-model="form.bankDeposit" type="textarea" readonly />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="银行卡号" prop="bankCard">-->
<!--              <el-input v-model="form.bankCard"  readonly/>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->

<!--        <el-row>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="银行编码" prop="bankCode">-->
<!--              <el-input v-model="form.bankCode"  readonly/>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="银行名称" prop="bankName">-->
<!--              <el-input v-model="form.bankName" readonly/>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->


<!--        <el-row>-->
<!--          <el-col :span="8">-->
<!--            <el-form-item label="银行卡姓名" prop="bankUserName" readonly>-->
<!--              <el-input v-model="form.bankUserName"  readonly />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="8">-->
<!--            <el-form-item label="银行卡身份证号" prop="bangkUserIdcard" readonly>-->
<!--              <el-input v-model="form.bangkUserIdcard"  readonly/>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="8">-->
<!--            <el-form-item label="银行卡绑定手机号" prop="bankUserPhone" readonly>-->
<!--              <el-input v-model="form.bankUserPhone" readonly />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->

<!--        <el-row>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="结算周期" prop="accountDay">-->
<!--              <el-input v-model="form.accountDay"readonly />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="上次结算时间" prop="accountLastTime">-->
<!--              <el-date-picker clearable size="small"-->
<!--                              v-model="form.accountLastTime"-->
<!--                              type="date"-->
<!--                              value-format="yyyy-MM-dd"-->
<!--                              placeholder="选择上次结算时间"-->
<!--                              disabled-->
<!--              >-->
<!--              </el-date-picker>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->


      </el-form>
      <div slot="footer" class="dialog-footer">
<!--        <el-button type="primary" @click="submitForm">确 定</el-button>-->
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改邀请码对话框 -->
    <el-dialog :close-on-click-modal="false" title="修改邀请码" :visible.sync="openAgentCode" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="邀请码" prop="agentCode">
          <el-input v-model="form.agentCode" placeholder="请输入邀请码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAgentCodeForm">确 定</el-button>
        <el-button @click="cancelAgentCode">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 门店展示 -->
    <el-dialog :close-on-click-modal="false" title="门店展示" :visible.sync="showVisible" width="800px" append-to-body @close="handleStoreClose">
      <imageUpload ref="storeRef" @input="handleStoreInput" :isShowTip="false"></imageUpload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitStoreList">确 定</el-button>
        <el-button @click="cancelStoreShow">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStore, getStore, logicDelStore, addStore, updateStore, exportStore,updateAgentCode } from "@/api/store/store";
import { addSaleRoom, deleteSaleRoom, updateSaleRoom } from '@/api/store/saleroom.js'
export default {
  name: "Store",
  data() {
    return {
      serviceItem:'',
      tableHeight:0,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 门店表格数据
      storeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //是否显示修改邀请码对话框
      openAgentCode: false,
      // 运营状态字典
      showStateOptions: [],
      // 门店状态字典
      storeStateOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeName: null,
        storePhone: null,
        agentCode: null,
        addressName: null,
        brandDetail: null,
        showState: null,
        storeState: null,
        consumption: null,
        serviceItem: null,
        businessStart: null,
        businessEnd: null,
        location: null,
        provinceName: null,
        provinceCode: null,
        cityName: null,
        cityCode: null,
        latitude: null,
        longitude: null,
        geoCode: null,
        storeLevel: null,
        effectLevel: null,
        environmentLevel: null,
        serviceLevel: null,
        bankCard: null,
        bankCode: null,
        bankName: null,
        bankDeposit: null,
        bankUserName: null,
        bangkUserIdcard: null,
        bankUserPhone: null,
        accountDay: null,
        accountLastTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        agentCode: [
          { required: true, message: "邀请码不能为空", trigger: "blur" }
        ]
      },
      showVisible: false,
      storeImgList: '',
      currentid: '',//当前门店展示id
      isStoreEdit: false //修改状态
    };
  },
  created() {
    this.getList();
    this.calHeight()
      this.getDicts("jy_operation_state").then(response => {
      this.showStateOptions = response.data;
    });
    this.getDicts("jy_store_state").then(response => {
      this.storeStateOptions = response.data;
    });
  },
  watch: {
    'showSearch':'calHeight'
  },
  methods: {
    calHeight () {
          this.$nextTick(() => {
              const rect = this.$refs.appcontainer.getBoundingClientRect();
              let height= this.$refs.queryForm.$el.offsetHeight;
              this.tableHeight = rect.height-height-120;
          })
      },
    /** 查询门店列表 */
    getList() {
      this.loading = true;
      listStore(this.queryParams).then(response => {
        this.storeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        storeImage: null,
        storeBacImage: null,
        businessImage:null,
        storeName: null,
        storePhone: null,
        addressName: null,
        agentCode: null,
        brandDetail: null,
        showState: null,
        storeState: null,
        consumption: null,
        serviceItem: null,
        businessStart: null,
        businessEnd: null,
        location: null,
        provinceName: null,
        provinceCode: null,
        cityName: null,
        cityCode: null,
        latitude: null,
        longitude: null,
        geoCode: null,
        storeLevel: null,
        effectLevel: null,
        environmentLevel: null,
        serviceLevel: null,
        bankCard: null,
        bankCode: null,
        bankName: null,
        bankDeposit: null,
        bankUserName: null,
        bangkUserIdcard: null,
        bankUserPhone: null,
        accountDay: null,
        accountLastTime: null,
        delState: null,
        delUser: null,
        delType: null,
        delTime: null,
        createBy: null,
        createType: null,
        createTime: null,
        updateBy: null,
        updateType: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.showSearch=false;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加门店";
    },
    /** 查看按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStore(id).then(response => {
        this.form = response.data;
        this.open = true;
        let arr = JSON.parse(response.data.serviceItem)
        var str = ''
        for(var i = 0; i < arr.length; i++){
          str = str+arr[i].dictLabel+" "
        }
        this.serviceItem = str
        this.title = "查看门店";
      });
    },
    /** 跳转到门店的产品 */
    handleToProduct(row) {
      this.$router.push({ path: '/store/storegoods', query: { id: row.id }})
    },
    /** 跳转到门店技师 */
    handleToTechnician(row) {
      this.$router.push({ path: '/store/technician', query: { id: row.id }})
    },
      /** 提交按钮 */
      submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStore(this.form).then(response => {
              this.msgSuccess("查看成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStore(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return logicDelStore(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 修改邀请码 **/
    updateAgentCode(row){
      this.reset();
      getStore(row.id).then(response => {
        this.form = response.data;
        this.openAgentCode = true;
      });
    },
    // 取消按钮
    cancelAgentCode() {
      this.openAgentCode = false;
      this.reset();
    },
    //保存邀请码
    submitAgentCodeForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          updateAgentCode(this.form).then(response => {
            this.msgSuccess("修改邀请码成功");
            this.openAgentCode = false;
            this.getList();
          });
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有门店数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportStore(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    // 门店展示
    handleStoreShow(row) {
      //存在门店展示时为修改，否则为新增
      this.currentid = row.id
      this.showVisible = true
      //上传空图片会导致接口返回的时候row.storeShowImage = ','
      if(row.storeShowImage && row.storeShowImage != ',') {
        this.isStoreEdit = true
        this.$nextTick(() => {
          //nextTick后还是没有获取ref，可能走的微任务，先使用setTimeout在异步队列中获取
          setTimeout(() => {
            this.$refs['storeRef'].handleMulEdit(row.storeShowImage)
          },0)
          
        })
      }else {
        this.isStoreEdit = false
      }
    },
    //取消门店展示弹窗
    cancelStoreShow() {
      this.showVisible = false
      // this.$refs['storeRef'].handleStoreClose()
      this.handleStoreClose()
    },
    handleStoreInput(value) {
      // console.log(value)
      this.storeImgList = value
      // this.storeImgList.push(value)
    },
    //新增门店展示
    submitStoreList() {
      
      // const imgstr = this.storeImgList.join(',')
      // const data = {
      //   storeId: Number(this.currentid),
      //   image: this.storeImgList
      // }
      if(!this.storeImgList) {
        // this.$message
        this.$message({
          message: '请上传图片或上传正确图片',
          type: 'warning'
        });
        return
      }
      this.loading = true
      if(this.isStoreEdit) {
        const data = {
          id: Number(this.currentid),
          storeShowImage: this.storeImgList
        }
        // const formdata = new FormData()
        // formdata.append('id',Number(this.currentid))
        // formdata.append('storeShowImage',this.storeImgList)
        updateSaleRoom(data).then(() => {
          this.msgSuccess("修改成功");
        }).finally(() => {
          this.loading = false
          this.showVisible = false
          this.handleStoreClose()
          this.getList();
        })
      } else {
        const formdata = new FormData()
        formdata.append('storeId',Number(this.currentid))
        formdata.append('image',this.storeImgList)
        addSaleRoom(formdata).then(res => {
          this.msgSuccess("新增成功");
        }).finally(() => {
          this.loading = false
          this.showVisible = false
          this.handleStoreClose()
          this.getList();
        })
      }
    },
    //门店展示关闭处理
    handleStoreClose() {
      this.$refs['storeRef'].clearFile()
      this.isStoreEdit = false
    },
    //删除门店展示，使用修改接口删除接口暂不用
    deleteStoreImg() {
      const data = {
        storeId: this.currentid,
        image: this.storeImgList
      }
      deleteSaleRoom(data).then(() => {
        this.msgSuccess("删除成功");
      })
    },
    toStaffList(row) {
      this.$router.push({
        path: '/store/store/staff?id='+row.id
      })
      console.log(row)
    }
  }
};
</script>
